# -*- coding: utf-8 -*-
# @Time    : 2020/5/25 下午6:14
# @Author  : Kevin Liu
# @Email   : liuwenlongfox@163.com
import json
import os

import requests,yaml
class Curl:
    def __init__(self,config_file):
        file = open(config_file,'r',encoding='utf-8')
        self.config = yaml.load(file)
    def parse_config(self):
        return self.config
    def find_token(self,var_dict):
        config = self.config
        token_key_in_response = config.get('token').get('token_key_in_response')
        for key,value in var_dict.items():
            if key==token_key_in_response:
                return value
            else:
                if isinstance(value,dict):
                    token = self.find_token(value)
                    if token is not None:
                        return token
    def get_token(self):
        try:
            toke_file = open(os.path.join(os.path.abspath('.'),'token'),'r')
            token = str(toke_file.readline())
            if self.verify_token(token):
                return token
        except Exception as e:
            print('open file failed',str(e))
            return None
        finally:
            toke_file.close()
        #apply for new token
        config = self.config
        api_url = self.config.get('token').get('base_url')+self.config.get('token').get('url')
        timeout = self.config.get('config').get('timeout')
        method = self.config.get('token').get('method')
        body = self.config.get('token').get('body')
        headers = self.config.get('token').get('headers')
        params = self.config.get('token').get('params')
        # print(api_url,method,body,headers)
        result=requests.request(method, api_url, headers=headers, data=body, params=params, timeout=timeout)

        token = self.find_token(json.loads(result.text))

        if token:
            try:
                toke_file = open(os.path.join(os.path.abspath('.'), 'token'), 'w')
                toke_file.write(token)
            except Exception as e:
                print('write token failed', str(e))
                return None
            finally:
                toke_file.close()
            return token
        else:
            print('获取token失败')
            return None
    def verify_token(self,token):
        config=self.config
        api_url = config.get('verify').get('base_url')+config.get('verify').get('url')
        timeout = config.get('verify').get('timeout')
        method = config.get('verify').get('method')
        body = config.get('verify').get('body')
        headers = config.get('verify').get('headers')
        params = config.get('verify').get('params')
        token_key_in_request = config.get('verify').get('token_key_in_request')
        headers[token_key_in_request] = token
        result = requests.request(method, api_url, headers=headers,timeout=timeout,verify=False)
        print(json.loads(result.text))
        status = json.loads(result.text).get('status')
        if status == 0:
            return True
        else:
            return False

    def send_requests(self,case_config,token):
        config = self.config
        token_key_in_request = self.config.get('token').get('token_key_in_request')
        if not token:
            return None
        api_url = self.config.get('config').get('base_url')+case_config.get('url')
        timeout = self.config.get('config').get('timeout')
        method = case_config.get('method')
        body = case_config.get('body')
        headers = case_config.get('headers')
        headers[token_key_in_request]=token
        print(api_url,method,body,headers)
        params = case_config.get('params')
        result = requests.request(method, api_url, headers=headers, data=body, params=params, timeout=timeout)
        # print(result.text)
        if result.status_code == 200:
            return result
        else:
            print('发送请求失败')
            return None

if __name__=="__main__":
    curl = Curl('./config_dir/app.yaml')
    print(curl.get_token())
